<?php

!defined('IN_SYSTEM') && exit('Access denied');

class class_upload {

    private $exts = array();

    private $error = '';

    private $current_file_ext = '';

    /**
     * 设置允许上传的附件类型
     *
     * 快捷设置：image,office
     */
    public function setAllowExt($exts) {
        if (in_array($exts,array('image','office'))) {
            switch ($exts) {
                case 'image':
                    $exts = array('jpg','jpeg','png','gif');
                break;

                case 'office':
                    $exts = array('doc','docs','xls','xlsx','ppt','pptx');
                break;
            }
        } else {
            if(!is_array($exts)) {
                $exts = explode(',',$exts);
            }
        }

        $this->exts = $exts;
    }
    public function getAllowExt() {
        return $this->exts;
    }

    public function upload($file,$filepath) {
        if (empty($this->exts)) $this->allowExt('image');
        $file = & $_FILES[$file];
        if (!is_uploaded_file($file['tmp_name'])) {
            $this->error = '没有文件被上传';
            return false;
        }
        $tmp_name = $file['tmp_name'];
        $this->current_file_ext = strtolower(end(explode('.',$file['name'])));
        if ($file['error'] != '0') {
            if (in_array($file['error'],array(4,6,7))) $file['error'] = '3';
            if ($file['error'] == '2') $file['error'] = '1';
            
            $this->error = str_replace(array(1,3),array('文件太大','上传失败，未知原因'),$file['error']).$file['error'];
            $this->error = $file['error'];
            @unlink($tmp_name);
            return false;
        }
        if (!in_array($this->current_file_ext,$this->exts,1)) {
            $this->error = '该类型文件不允许被上传';
            @unlink($tmp_name);
            return false;
        }

        $real_filepath .= "{$filepath}.{$this->current_file_ext}";

        $path = dirname($real_filepath);
        if (!is_dir($path)) mkdir($path,0777,1);

        if (!move_uploaded_file($file['tmp_name'],$real_filepath)) {
            $this->error = '上传失败，服务器发生错误';
            @unlink($tmp_name);
            return false;
        }

        @unlink($tmp_name);

        return true;
    }

    public function getError() {
        return $this->error;
    }

    public function getFileExt() {
        return $this->current_file_ext;
    }
}